//
//  EmotionCollectionView.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/27.
//  Copyright © 2016年 Tiffany. All rights reserved.
//

import UIKit

class EmotionCollectionView: UICollectionView {
    
    var scrollViewDidScrollClosure: ((NSIndexPath) -> ())?
    
    //    var indexSection: Int = 0
    
    let EmotionCollectionViewCellID = "EmotionCollectionViewCell"
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //注册cell
        self.registerClass(EmotionCollectionViewCell.self, forCellWithReuseIdentifier: EmotionCollectionViewCellID)
        
        self.dataSource = self
        self.delegate = self
        
        self.showsHorizontalScrollIndicator = false
        self.pagingEnabled = true
        self.bounces = false
        
        //清除背景颜色
        self.backgroundColor = UIColor.clearColor()
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.scrollDirection = .Horizontal
        
        layout.itemSize = CGSizeMake(SCREENW, emotionKeyboardViewH - emotionToolBarH)
        
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        
        
    }
    
    
}


extension EmotionCollectionView: UICollectionViewDataSource ,UICollectionViewDelegate{
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return EmotionKeyboardViewModel.sharViewModel.allEmotions.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return EmotionKeyboardViewModel.sharViewModel.allEmotions[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmotionCollectionViewCellID, forIndexPath: indexPath) as! EmotionCollectionViewCell
        
        cell.emotions = EmotionKeyboardViewModel.sharViewModel.allEmotions[indexPath.section][indexPath.item]
        
        cell.indexPath = indexPath
        
        //        print(EmotionKeyboardViewModel.sharViewModel.allEmotions[indexPath.section][indexPath.item])
        
        //        cell.backgroundColor = RandomColor
        
        return cell
    }
    
    // MARK: - scrollViewDidScroll
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //collectionView 的中心点
        var center = scrollView.center
        
        //cell 在滚动时,contentOffset 会一直增加,要确保cell在滚动时也要包含 collectionView 的中心点,所以...
        center.x += scrollView.contentOffset.x
        
        //拿到可见的cell
        let cells = self.visibleCells()
        
        let indexPath: NSIndexPath
        
        //判断可见 cell 的个数
        if cells.count == 2{
            
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            //判断是否包含 collectionView 的中心点
            if CGRectContainsPoint(firstCell.frame, center){
                //求出cell所对应的IndexPath
                indexPath = self.indexPathForCell(firstCell)!
            }else{
                indexPath = self.indexPathForCell(lastCell)!
            }
            
        }else{
            
            indexPath = self.indexPathForCell(cells.first!)!
        }
        
        //        print(indexPath.section)
        //        self.indexSection = indexPath.section
        
        //执行闭包
        scrollViewDidScrollClosure?(indexPath)
    }
}


class EmotionCollectionViewCell: UICollectionViewCell {
    
    //表情按钮数组
    var emotionButtons: [PopViewButton] = []
    
    //给表情按钮设置数据
    //每一页的表情数组
    var emotions: [EmotionModel]?{
        
        didSet{
            
            guard let emot = emotions else{
                
                return
            }
            
            //解决cell重用的问题
            for button in emotionButtons{
                
                button.hidden = true
            }
            
            //emotion是每一个表情模型
            for (index,emotion) in emot.enumerate(){
                
                //拿到不同的按钮添加图片
                let button = emotionButtons[index]
                
                
                //显示按钮
                button.hidden = false
                
                // ****** 给自定义按钮的 emotion 属性赋值 *******
                button.emotion = emotion
                
//                button.titleLabel?.font = UIFont.systemFontOfSize(33)
//                
//                                if emotion.type == "1"{
//                
//                                    //emoji 表情
//                                    button.setTitle((emotion.code! as NSString).emoji(), forState: UIControlState.Normal)
//                                    button.setImage(nil, forState: UIControlState.Normal)
//                                }else{
//                
//                                    let image = UIImage(named: "\(emotion.folderName ?? "")/\(emotion.png ?? "")", inBundle: EmotionKeyboardViewModel.sharViewModel.loadBundle(), compatibleWithTraitCollection: nil)
//                                    button.setImage(image, forState: UIControlState.Normal)
//                                    button.setTitle(nil, forState: UIControlState.Normal)
//                                }
            }
        }
    }
    
    var indexPath: NSIndexPath?{
        didSet{
            //            countLabel.text = "第\(indexPath!.section)组~第\(indexPath!.item)列"
            textLabel.hidden = indexPath?.section != 0
        }
    }
    
    // MARK: - 点击子按钮的方法
    @objc private func didClickChildButton(button: PopViewButton){
        
//        print(button.emotion!.chs)
        
        //        let popView = EmotionPopView.popView()
        
        EmotionKeyboardViewModel.sharViewModel.saveRecentEmotins(button.emotion!)
        
        //点击表情按钮发送的通知
        NSNotificationCenter.defaultCenter().postNotificationName(ClickEmotionButtonNotification, object: nil, userInfo: ["emotion":button.emotion!])
        
        //取到最上层的window
        let window = UIApplication.sharedApplication().windows.last
        
        //进行坐标的转换 (因为 frame 是相对于父控件来说的,而 bounds 是相对于自己来说的)
        //        let rect = button.superview!.convertRect(button.frame, toView: window)
        let rect = button.convertRect(button.bounds, toView: window)
        
        popView.center.x = button.center.x
        //        popView.center.x = CGRectGetMidX(rect)
        //        popView.frame.origin.y = CGRectGetMaxY(button.frame) - popView.frame.height
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        
        window?.addSubview(popView)
        
        //给popView里的按钮赋值
        popView.popViewButton.emotion = button.emotion
        
        //        contentView.addSubview(popView)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(0.25) * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.popView.removeFromSuperview()
        }
    }
    
    
    private func addChildButtons(){
        
        let count = EmotionKeyboardItemCount
        
        for _ in 0..<count {
            
            let button = PopViewButton()
            
            //给按钮添加点击事件
            button.addTarget(self, action: "didClickChildButton:", forControlEvents: UIControlEvents.TouchUpInside)
            
            //设置按钮背景为随机色
            //            button.backgroundColor = RandomColor
            
            emotionButtons.append(button)
            
            contentView.addSubview(button)
        }
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemW = self.contentView.bounds.width / CGFloat(EmotionKeyboardCol)
        let itemH = (self.contentView.bounds.height - 25) / CGFloat(EmotionKeyboardRow)
        
        for (index,value) in emotionButtons.enumerate(){
            
            //行索引
            let rowIndex = index / EmotionKeyboardCol
            //列索引
            let colIndex = index % EmotionKeyboardCol
            
            let itemX = CGFloat(colIndex) * itemW
            let itemY = CGFloat(rowIndex) * itemH
            value.frame = CGRectMake(itemX, itemY, itemW, itemH)
        }
        
        //设置删除按钮的位置
        let deleteItemX = self.frame.width - itemW
        let deleteItemY = self.frame.height - itemH - 25
        
        deleteButton.frame = CGRectMake(deleteItemX, deleteItemY, itemW, itemH)
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addChildButtons()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        //添加控件
        contentView.addSubview(textLabel)
        contentView.addSubview(deleteButton)
        
        //添加约束
        textLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        
        //添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "ResponseToLongPress:")
        // 长按手势最短的触发时间
        //        longPress.minimumPressDuration = 3
        contentView.addGestureRecognizer(longPress)
    }
    
    // MARK: - 长按手势响应
    @objc private func ResponseToLongPress(ges:UILongPressGestureRecognizer){
        
        //1.获取当前手指的位置
        let loc = ges.locationInView(ges.view)
        
        //2.遍历表情按钮,判断当前的按钮位置是否包含手指的位置
        func buttonWithLocation(loc: CGPoint) -> PopViewButton?{
            for button in emotionButtons{
                
                if CGRectContainsPoint(button.frame, loc){
                    
//                    print("在范围里面\(loc)")
                    return button
                }
            }
            return nil
        }
        
        guard let  button = buttonWithLocation(loc) else{
            
            //如果手指不在按钮区域则移除popView(其实就是指删除按钮)
            popView.removeFromSuperview()
//            print("不在范围里面\(loc)")
            return
        }
        
        // MARK - *** 解决最近表情为空 长按后会弹出popView的bug
        if button.hidden {
            return
        }
        
        switch ges.state {
        case .Began,.Changed:
            
            if popView.popViewButton.emotion == button.emotion{
                //如果手指在同一个按钮范围内,就不需要一直进行坐标转换了(只进行一次就够了)
                return
            }
            //取到最上层的window
            let window = UIApplication.sharedApplication().windows.last
            
            //进行坐标的转换 (因为 frame 是相对于父控件来说的,而 bounds 是相对于自己来说的)
            let rect = button.convertRect(button.bounds, toView: window)
            
                                popView.center.x = button.center.x
//            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            
            window?.addSubview(popView)
            
            //给popView里的按钮赋值
            popView.popViewButton.emotion = button.emotion
            
        default:
            popView.removeFromSuperview()
            
            //长按结束 通知表情
            NSNotificationCenter.defaultCenter().postNotificationName(ClickEmotionButtonNotification, object: nil, userInfo: ["emotion":button.emotion!])
            
            //清空表情
            popView.popViewButton.emotion = nil
            
        }
}

    @objc private func didClickDeleteButton(){
        
        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(ClickDeleteButtonNotification, object: nil)
    }
//懒加载
//    private lazy var countLabel: UILabel = UILabel(textFont: 30, textColor: UIColor.darkGrayColor())
private lazy var textLabel: UILabel = {
    
    let label = UILabel(textFont: 13, textColor: UIColor.lightGrayColor())
    
    label.text = "最近使用的表情"
    
    return label
}()

//删除按钮
private lazy var deleteButton: UIButton = {
    
    let button = UIButton()
    
    //给删除按钮添加点击事件
    button.addTarget(self, action: "didClickDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
    
    button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
    button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
    
    return button
}()

//popView
private lazy var popView: EmotionPopView = EmotionPopView.popView()

}


